<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
%>
<div id="material_edit_page" class="row-fluid" style="height: inherit;margin:0px">
    <form class="form-horizontal" id="baseInfor" name="baseInfor" method="post" target="_ifr" style="border-bottom: solid 2px #3b73af;">
        <input type="hidden" id="id" name="id" value="${outLiNing.id }" />
        <input type="hidden" id="outliningNo" name="outliningNo" value="${outLiNing.outliningNo }" />
        <input type="hidden" id="state" name="state" value="${outLiNing.state }" />
        <div class="row" style="margin:0;padding:0;">
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="supplierId" >供应商：</label>
                <div class="controls">
                    <div class="span12 required" style=" float: none !important;">
                        <input class="span10" type="text"  id="supplierId" name="supplierId" value="${receipt.supplyId}" placeholder="供应商" />
                    </div>
                </div>
            </div>
            <div class="control-group span6" style="display: inline">
				<label class="control-label" for="userId">操作人：</label>
				<div class="controls">
					<div class="span12 required" style=" float: none !important;">
						<input type="text" class="span10" name="userId" id="userId" placeholder="操作人" value="${distribution.userId}" />
					</div>
				</div>
			</div>
        </div>     
        <div class="row" style="margin:0;padding:0;">       	
             <div class="control-group span6" style="display: inline">
                <label class="control-label" for="operationTime">操作时间：</label>
                <div class="controls">
                    <div class="required">
                        <input class="form-control date-picker" id="operationTime" name="operationTimeStr" type="text" value="${outLiNing.operationTimeStr}" placeholder="操作时间" class="span8" />
                    </div>
                </div>
            </div>
            <div class="control-group span6" style="display: inline">
	            <label class="control-label" for="remark" >备注：</label>
	            <div class="controls">
	                 <input type="text" id="remark" class="span10" name="remark" value="${outLiNing.remark }"  placeholder="备注信息" />
	            </div>
	        </div>
        </div>
        <div style="margin-bottom:5px;margin-left:10px;">
            <span class="btn btn-info" id="formSave" onclick="saveForm();">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
            <span class="btn btn-info" id="outformSubmit" onclick="outformSubmitBtn();">
		        <i class="ace-icon fa fa-check bigger-110"></i>&nbsp;提交
            </span>
        </div>
    </form>    
     <!-- 入库单搜索div -->
    <div id="materialDiv" style="margin:10px;">
        <!-- 下拉框 -->
        <label class="inline" for="materialInfor">物料：</label>
        <input type="text" id = "materialInfor" name="materialInfor" style="width:350px;margin-right:10px;" />
        <button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
            <i class="icon-plus" style="margin-right:6px;"></i>添加
        </button>
    </div>
    <div id="grid-div-c" style="width:100%;margin:0px auto;">
        <div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
            <div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
        <table id="grid-table-c" style="width:100%;height:100%;"></table>
        <div id="grid-pager-c"></div>
    </div>
</div>
<iframe src="about:blank" name="_ifr" height="0" class="hidden"></iframe>
<script type="text/javascript" src="<%=path%>/static/js/techbloom/wms/outlining/outlining_detail.js"></script>
<script type="text/javascript">
    var context_path = '<%=path%>';
    var oriData;      //表格数据
    var _grid;        //表格对象
    var lastsel2;
    var preStatus=${INSTORE.preStatus==null?0:INSTORE.preStatus};
    var selectData = 0;   //存放物料选择框中的值
    var selectParam = "";  //存放之前的查询条件

    $("#baseInfor input[type=radio]").uniform();
    $("#baseInfor input[type=radio][name=preStatus][value="+preStatus+"]").attr("checked",true).trigger("click");
    $(".date-picker").datetimepicker({format: 'YYYY-MM-DD HH:mm:ss',useMinutes:true,useSeconds:true});


    function saveForm() {
        var bean = $("#baseInfor").serialize();
        if ($("#baseInfor").valid()) {
            saveLining(bean);
        }     
	}
    
	function saveLining(bean) {
        $.ajax({
			url : context_path + "/outLiNing/saveOutLiNing.do",
			type : "POST",
			data : bean,
 			success : function(data) {
				if (Boolean(data.result)) {
					layer.msg("表头保存成功！", {icon : 1});
					$("#baseInfor #outliningNo").val(data.planCode);
				    $("#baseInfor #id").val(data.id);
					$("#baseInfor #state").val("2");
					$("#grid-table").jqGrid("setGridParam", {
                       postData: {queryJsonString:""}
                    }).trigger("reloadGrid");
				} else {
					layer.alert(data.msg, {icon : 2});
				}
			},
			error : function(XMLHttpRequest) {
				alert(XMLHttpRequest.readyState);
				alert("出错啦！！！");
			}
		});
    }
    $("#baseInfor").validate({
        ignore: function(i,dom){
            var r_dom ="";
            var crossdockTypeSelect_id = $("#baseInfor #crossdockTypeSelect").val();
            if(dom.id == "saleId" && crossdockTypeSelect_id != "WMS_CROSSDOCK_SCDD" && crossdockTypeSelect_id!="WMS_CROSSDOCK_SSDD"){
                r_dom = dom;
            }
            return r_dom;
        },
        rules: {
            "createTime": {
                required: true,
            },
            "crossdockTypeSelect": {
                required: true,
            },
            "saleId":{
                required: true,
            }
        },
        messages: {
            "createTime": {
                required: "请输入越库时间!",
            },
            "crossdockTypeSelect": {
                required: "请选择越库计划类型",
            },
            "saleId":{
                required: "请选择订单",
            }
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        }
    });
    //清空物料多选框中的值
    function removeChoice(){
        $("#s2id_materialInfor .select2-choices").children(".select2-search-choice").remove();
        $("#materialInfor").select2("val","");
        selectData = 0;
    }

    $('[data-rel=tooltip]').tooltip();
    $('#materialInfor').select2({
        placeholder : "请选择物料",//文本框的提示信息
        minimumInputLength : 0, //至少输入n个字符，才去加载数据
        allowClear : true, //是否允许用户清除文本信息
        multiple: true,
        closeOnSelect:false,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax : {
            url : context_path + '/material/getMaterialSelectList',
            dataType : 'json',
            delay : 250,
            data : function(term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                selectParam = term;
                return {
                    crossType:$("#baseInfor #crossType").val(),
                    saleId:$("#baseInfor #saleId").val(),
                    receiptId:$("#baseInfor #receiptId").val(),
                    queryString : term, //联动查询的字符
                    pageSize : 15, //一次性加载的数据条数
                    pageNo : pageNo, //页码
                    time : new Date()
                    //测试
                }
            },
            results : function(data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results : res,
                        more : more
                    };
                } else {
                    return {
                        results : {
                            "id" : "0",
                            "text" : "没有更多结果"
                        }
                    };
                }

            },
            cache : true
        }
    });

    $('#materialInfor').on("change",function(e){
        var datas=$("#materialInfor").select2("val");
        selectData = datas;
        var selectSize = datas.length;
        if(selectSize>1){
            var $tags = $("#s2id_materialInfor .select2-choices");   //
            //$("#s2id_materialInfor").html(selectSize+"个被选中");
            var $choicelist = $tags.find(".select2-search-choice");
            var $clonedChoice = $choicelist[0];
            $tags.children(".select2-search-choice").remove();
            $tags.prepend($clonedChoice);

            $tags.find(".select2-search-choice").find("div").html(selectSize+"个被选中");
            $tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
            $tags.find(".select2-search-choice").find("a").attr("href","#");
            $tags.find(".select2-search-choice").find("a").attr("onclick","removeChoice();");
        }
        //执行select的查询方法
        $("#materialInfor").select2("search",selectParam);
    });

    //工具栏
    $("#__toolbar__-c").iToolBar({
        id:"__tb__01",
        items:[
            {label:"删除", onclick:delDetail}
        ]
    });
    _grid =  $("#grid-table-c").jqGrid({
        url : context_path + "/outLiNing/detailList.do?pId="+$("#baseInfor #id").val(),
        datatype : "json",
        colNames : [ "详情主键","物料主键","物料编号","物料名称","数量"],
        colModel : [
            {name : "id",index : "id",width : 55,hidden:true},
            {name : "materialId",index : "materialId",width : 55,hidden:true},
            {name : "materialNo",index:"materialNo",width : 50},
            {name : "materialName",index:"materialName",width : 50},
            {name : "amount",index:"amount",width : 50,editable : true,editrules: {custom: true, custom_func: numberRegex},
                editoptions: {
                    size: 25, dataEvents: [{
                        type: "blur",
                        fn: function (e) {
                            var $element = e.currentTarget;
                            var $elementId = $element.id;
                            var rowid = $elementId.split("_")[0];
                            var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
                            if (!reg.test($("#" + $elementId).val())) {
                                layer.alert("非法的数量！(注：可以有两位小数的正实数)");
                                return;
                            }
                            var id = $("#grid-table-c").jqGrid('getGridParam', 'selrow');
                            var rowData = $("#grid-table-c").jqGrid('getRowData', id).avalibleAmount;
                            var materialId = $("#grid-table-c").jqGrid('getRowData', id).materialId;
                            $.ajax({
                                type: "POST",
                                dataType: "json",
                                url: context_path + '/crossDockPlan/saveamount',
                                data: {amount: $("#" + rowid + "_amount").val(), avalibleAmount: rowData, id: id,materialId:materialId,lastamount:lastamount},
                                success: function (data) {
                                    if(!data.result){
                                        layer.alert(data.msg);
                                    }
                                    $("#grid-table-c").jqGrid('setGridParam',
                                        {
                                            url:context_path + '/crossDockPlan/DetailList',
                                            postData: {qId:$('#baseInfor #id').val(),queryJsonString:""}
                                        }
                                    ).trigger("reloadGrid");
                                }
                            })
                        }
                    },
                        {
                            type: 'focus',
                            fn: function (e) {
                                console.dir(18790);
                                var $element = e.currentTarget;
                                var $elementId = $element.id;
                                var rowid = $elementId.split("_")[0];
                                var aa = $("#" + rowid + "_amount").val();
                                if(aa!=""){
                                    lastamount = aa;
                                }
                            }
                        }]
                }
            }
        ],
        rowNum : 20,
        rowList : [ 10, 20, 30 ],
        pager : "#grid-pager-c",
        sortname : "id",
        sortorder : "asc",
        altRows: true,
        viewrecords : true,
        autowidth:true,
        multiselect:true,
        multiboxonly: true,
        loadComplete : function(data){
            var table = this;
            setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
            oriData = data;
            $(window).triggerHandler("resize.jqGrid");
        },
        cellEdit: true,
        cellsubmit : "clientArray",
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#grid-table-c").navGrid("#grid-pager-c",{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd("#grid-pager-c",{
            caption:"",
            buttonicon:"ace-icon fa fa-refresh green",
            onClickButton: function(){
                $("#grid-table-c").jqGrid("setGridParam",
                    {
                        url:context_path + "/outStoragePlan/DetailList",
                        postData: {qId:$("#baseInfor #id").val(),queryJsonString:""} //发送数据  :选中的节点
                    }
                ).trigger("reloadGrid");
            }
        });

    $(window).on("resize.jqGrid", function () {
        $("#grid-table-c").jqGrid("setGridWidth", $("#grid-div-c").width() - 3 );
        var height = $(".layui-layer-title",_grid.parents(".layui-layer")).height()+
                     $("#baseInfor").outerHeight(true)+$("#materialDiv").outerHeight(true)+
                     $("#grid-pager-c").outerHeight(true)+$("#fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+$("#gview_grid-table-c .ui-jqgrid-hbox").outerHeight(true);
                     $("#grid-table-c").jqGrid("setGridHeight",_grid.parents(".layui-layer").height()-height);
    });
    $(window).triggerHandler("resize.jqGrid");

    var lastamount = 0.00;
    //添加入库单详情
    function addDetail(){
        var id = $("#baseInfor #id").val();
        if(id=="-1"||id==""){
            layer.alert("请先保存表单信息！");
            return;
        }
        if(selectData!=0){
            //将选中的物料添加到数据库中
            $.ajax({
                type:"POST",
                url:context_path + "/outLiNing/saveDetail.do",
                data:{pId:$("#baseInfor #id").val(),materialIds:selectData.toString()},
                dataType:"json",
                success:function(data){
                    removeChoice();   //清空下拉框中的值
                    if(Boolean(data.result)){
                        layer.msg("添加成功！",{icon:1});
                        //重新加载详情表格
                        $("#grid-table-c").jqGrid("setGridParam",
                            {
                                postData: {qId:$("#baseInfor #id").val(),rId:$("#baseInfor #receiptId").val()} //发送数据  :选中的节点
                            }
                        ).trigger("reloadGrid");
                    }else{
                        layer.alert("添加失败");
                    }
                }
            });
        }else{
            layer.alert("请选择物料！");
        }
    }

    //关闭当前窗口
    function closeWindowBtn(){
        layer.closeAll();
    }

    //数量输入验证
    function numberRegex(value, colname) {
        var regex = /^\d+\.?\d{0,2}$/;
        if (!regex.test(value)) {
            layer.alert("非法的数据,请输入整数");
            return [false, ""];
        }
        else  return [true, ""];
    }

    if($("#baseInfor #planCode").val()!=""){
        $.ajax({
            type:"POST",
            url:context_path + '/crossDockPlan/getOrderById',
            data:{id:$("#baseInfor #id").val(),crossType:$("#baseInfor #crossType").val()},
            success:function(data){
                $("#saleId").select2("data", {
                    id: data.id,
                    text: data.orderName
                });
            }
        })
    }
    
        $("#baseInfor #supplierId").select2({
        placeholder: "选择供应商",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/ASNmanage/getSelectSupply",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
    
     $("#baseInfor #userId").select2({
        placeholder: "选择操作人",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        width: 200,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/user/getUserSelect",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
$.ajax({
	 type:"POST",
	 url:context_path + "/outLiNing/findLiningById",
	 data:{id:$("#baseInfor #id").val()},
	 dataType:"json",
	 success:function(data){
			  $("#baseInfor #userId").select2("data", {
 			  id: data.userId,
 			  text: data.userName
             }); 
             $("#baseInfor #supplierId").select2("data", {
 			  id: data.supplierId,
 			  text:data.supplierName
             });
		}
	});
</script>